package com.xzp.gkrpc.transprot;

import com.xzp.gkrpc.Peer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

@Slf4j
public class HttpTransportClient implements TransportClient{
    private String url;

    @Override
    public void connect(Peer peer) {
        this.url = "http://" + peer.getHost() + ":" +peer.getPort();
    }

    @Override
    public InputStream write(InputStream data) {
        try {
            HttpURLConnection httpConn = (HttpURLConnection)new URL(this.url).openConnection();
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            httpConn.setUseCaches(false);
            httpConn.setRequestMethod("POST");
            httpConn.connect();
            // 把输入数据拷贝到httpConn的输出流中
            IOUtils.copy(data, httpConn.getOutputStream());
            int code = httpConn.getResponseCode();
            if(code == HttpURLConnection.HTTP_OK){
                // 获取接收到的数据
                log.info("HttpTransportClient successful receive data");
                return httpConn.getInputStream();
            }else{
                log.warn("HttpTransportClient fail to receive data");
                return httpConn.getErrorStream();
            }
        } catch (IOException e) {
            throw new IllegalStateException();
        }
    }

    @Override
    public void close() {

    }
}
